<template>
  <div>
  <el-table :data="filterTableData" style="width: 100%">
    <el-table-column label="提交日期" prop="date" />
    <el-table-column label="项目名称" prop="name" />
    <el-table-column
        prop="state"
        label="审核状态"
        width="100"
        column-key="state"
        :filters="[{ text: '审核中', value: '审核中' }, { text: '已通过', value: '已通过' }]"
        :filter-method="filterStatus"
    >
      <template #default="scope">
        <el-tag
            :type="scope.row.state === '审核中' ? 'primary' : 'success'"
            disable-transitions>{{scope.row.state}}</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="分数" prop="score" />
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" size="small" placeholder="Type to search" />
      </template>
      <template #default="scope">
        <!--修改项目-->
        <el-button  size="small" @click="dialogFormVisible = true; setFocus(scope.row)" type="primary" style="margin-right: 15px">修改</el-button>


        <el-button size="small" @click="setFocus(scope.row); go();" type="info">查看</el-button>
        <el-button size="small" @click="download(scope.row)" type="success">下载</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totalPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</div>
  <!--修改项目-->
  <el-dialog v-model="dialogFormVisible" title="项目修改">
    <el-form :model="form">
      <el-form-item label="项目题目" :label-width="formLabelWidth" :rules="[{required: true,}]">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="项目类型" :label-width="formLabelWidth" :rules="[{required: true,}]">
        <el-select v-model="form.type" placeholder="选择类别">
          <el-option label="国创" value="国创" />
          <el-option label="校创" value="校创" />
        </el-select>
      </el-form-item>
      <el-form-item label="起止时间" :label-width="formLabelWidth">
        <el-col :span="11">
          <el-form-item prop="date1">
            <el-date-picker
                v-model="form.startTime"
                type="date"
                label="Pick a date"
                placeholder="开始时间"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="date1">
            <el-date-picker
                v-model="form.endTime"
                type="date"
                label="Pick a date"
                placeholder="终止时间"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>
      <!--项目金额-->
      <el-form-item label="项目金额" :label-width="formLabelWidth">
        <el-input v-model="form.projectMoney" />
      </el-form-item>
      <!--自然基金-->
      <el-form-item label="自然基金" :label-width="formLabelWidth">
        <el-input v-model="form.natureFund" />
      </el-form-item>
      <!--合作单位-->
      <el-form-item label="合作单位" :label-width="formLabelWidth">
        <el-input v-model="form.cooperationUnit" />
      </el-form-item>



      <el-form-item label="提交项目" :label-width="formLabelWidth" :rules="[{required: true,}]">
        <el-upload
            ref="upload"
            class="upload-demo"
            action="#"
            :limit="1"
            :on-exceed="handleExceed"
            :auto-upload="false"
            @change="updateFile"
        >
          <template #trigger>
            <el-button type="primary">选择上传的文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip text-red">
              只能上传一个文件，新的文件会被覆盖
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="项目描述" :label-width="formLabelWidth">
        <el-input  type="textarea"  v-model="form.description"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false;onSubmit(this);">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, computed, ref, toRaw, inject} from 'vue'
import {ElMessage, genFileId, UploadInstance, UploadProps, UploadRawFile, ElTable} from "element-plus";
import axios, {Axios} from "axios";
import assert from "assert";

const reload = inject('reload')

interface Project {
  id: number
  date: string
  name: string
  state:string
  score:string
}
const dialogFormVisible = ref(false)
let selectedID = ref(0)

const formLabelWidth = '140px'
const search = ref('')
const filterTableData = computed(() =>
    tableData.filter(
        (data) =>
            !search.value ||
            data.name.toLowerCase().includes(search.value.toLowerCase())
    )
)
const handleDelete = (index: number, row: Project) => {
  confirm("该操作不可恢复，是否继续？");
  console.log(index, row)
  let item = toRaw(row)
  axios.get(`project/delete?projectId=${item.id}`,
      {
        headers: {
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      }).then(res => {
    if (res.data.code === 0) {
      reload()
    } else {
      ElMessage('删除失败');
    }
  })
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}


const tableData = reactive<Project[]>([

])

let updateKey = ref(1)
let currentPage = ref(1)
let pageSize = ref(5)
let totalPage = ref(10)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)

const set = ()=> {
  axios.get(`project/list?pageSize=${pageSize.value}&pageNum=${currentPage.value}`,
      {
        headers: {
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      }).then(res => {
    if (res.data.code === 0) {
      while (tableData.length != 0) tableData.pop();

      console.log(tableData);
      res.data.data.list.forEach(function (e) {
        let project: Project = {
          id: e.id,
          date: e.uploadTime.split(' ')[0],
          name: e.name,
          state: e.status=='1'?"通过":(e.status=='-1'?"不通过":"审核中"),
          score: e.score,
        };
        tableData.push(project);
      })
      console.log(res);
      totalPage.value = res.data.data.total;
      console.log(res.data.data.pageNum);
      // updateKey.value += 1;
      console.log('current page '+currentPage.value)
      console.log(filterTableData);
    } else {
      ElMessage('切换失败');
    }
  })
}
set()



const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  console.log(currentPage);
  axios.get(`project/list?pageSize=${val}&pageNum=${1}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
    console.log(tableData);
    if(res.data.code === 0) {
      while(tableData.length != 0) tableData.pop();

      console.log(tableData);
      res.data.data.list.forEach(function (e){
        let project:Project = {
          id: e.id,
          date: e.uploadTime.split(' ')[0],
          name: e.name,
          state: e.status=='1'?"通过":(e.status=='-1'?"不通过":"审核中"),
          score: e.score,
        };
        tableData.push(project);
      })
      totalPage.value = res.data.data.total;
      currentPage = res.data.pageNum;
      // updateKey.value += 1;
      console.log(filterTableData);
    }else {
      ElMessage('切换失败');
    }
  })
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)

  axios.get(`project/list?pageSize=${pageSize.value}&pageNum=${val}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
    console.log(tableData);
    if(res.data.code === 0) {
      while(tableData.length != 0) tableData.pop();

      console.log(tableData);
      res.data.data.list.forEach(function (e){
        let project:Project = {
          id: e.id,
          date: e.uploadTime.split(' ')[0],
          name: e.name,
          state: e.status=='1'?"通过":(e.status=='-1'?"不通过":"审核中"),
          score: e.score,
        };
        tableData.push(project);
      })
      totalPage.value = res.data.data.total;
      currentPage = res.data.pageNum;
      // updateKey.value += 1;
      console.log(filterTableData);
    }else {
      ElMessage('切换失败');
    }
  })
}

const downloadAttach = (flag: string, title:string) => {
  // 发送get请求
  console.log(flag)
  axios.get(`/project/download/${flag}`, {
    headers: {
      'Content-Type': 'application/json',
      'session':localStorage.getItem('ID'),
    },
    responseType: 'blob'
  })
      .then(res => {
        const blob = new Blob([res.data]);//处理文档流
        const disposition = decodeURI(res.headers['content-disposition']);
        let fileName = disposition.substring(disposition.indexOf('fileName=')+9, disposition.length);
        console.log(res);
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      })
      .catch(() => {
        alert("请求出错");
      })
  // alert(url);
}

const download = (row: Project) => {
  console.log(row)
  let item = toRaw(row);
  console.log(item);
  axios.get(`project?projectId=${item.id}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
    if(res.data.code === 0) {
      console.log(res.data);
      let length = res.data.data.filePath.toString().split('/').length;
      let flag = res.data.data.filePath.toString().split('/')[length-1];
      console.log(flag);

      downloadAttach(flag, item.name)
    }else {
      console.log("获取flag出错")
      ElMessage('下载失败');
    }
  })
}
const setFocus = (row:Project) => {
  console.log(row);
  selectedID = ref(row.id);
  console.log(selectedID.value);
}

//项目信息部分表格
let form = reactive({
  cooperationUnit: "cooperationUnit",
  filePath: "blah",
  memberFiveName: "5",
  memberFourName: "4",
  memberThreeName: "3",
  memberTwoName: "2",
  memberOneName: "1",
  startEndYear: "startEndYear",
  natureFund: "natureFund",
  startTime: "startTime",
  endTime: "endTime",
  description: "describe",
  projectMoney: "projectMoney",
  name: "",
  type: "",
})
var file = reactive({})
const onSubmit = () => {

  let info = form
  let projectID:number = selectedID.value;
  let infoJson = JSON.stringify(form);
  axios.post(`project/update?projectId=${projectID}`, info, {
    headers:{
      'Content-Type': 'application/json',
      'session':localStorage.getItem('ID'),
    }
  }).then(res=>{

    if(res.data.code === 0){
      // set()
      let param = new FormData();//创建form对象
      console.log("file"+file);
      console.log("projectid"+selectedID);
      if(JSON.stringify(file)==="{}") {
        ElMessage("上传失败，您没有选择传文件");
        return false;
      } else {
        param.append("file", file);//为创建的form对象增加上传的文件
        param.append("projectId", selectedID.value);//如果需要上传其他字段，在这里增加
        if(form.name==="")
        {
          ElMessage('项目名称不能为空');
          return false;
        }
        let config = { headers: { 'Content-Type': 'multipart/form-data', 'session':localStorage.getItem('ID'),  } }//修改请求头
        let url = "project/upload";
        console.log(param);
        axios.post(url, param, config).then((res) => {
          console.log(res, "res");
          if(res.data.code === 0) {
            ElMessage("修改成功");
            reload();
          } else {
            ElMessage(res.data.commonErrorCode.errorSuggestion);
          }
        });
      }
    } else {
      ElMessage(res.data.commonErrorCode.errorSuggestion);
    }
  })
}

import { getCurrentInstance } from "vue";
import router from "../router";
const { proxy } = getCurrentInstance();//获取原型
const Axios = proxy.$axios;//Axios就是挂在的原型（相当于vue2中的this.$axios）
const updateFile = (e) => {
  console.log(e);
  file = e.raw;//拿到上传的file
}
const go = () => {
  router.push ({
    path:"/display2",
    query:{
      paperId: selectedID.value
    }
  });
}
</script>
